package com.jxwifi.cloud.quickcleanserver.utils;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.basicactivity.BasicFrgment;

import butterknife.ButterKnife;

/**
 * Created by Administrator on 2019/5/20.
 */

public abstract class LazyLoadFragment extends BasicFrgment {

    /**
     * 视图是否已经初初始化
     */
    protected boolean isInit = false;
    protected boolean isLoad = false;
    protected final String TAG = "LazyLoadFragment";
    private View view;

    @Nullable
    @Override
    public View  onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(setContentView(), container, false);
        isInit = true;
        ButterKnife.bind(this, view);
        openEventBus();
        /**初始化的时候去加载数据**/
        //isCanLoadData();
        return view;
    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (getUserVisibleHint()) {
            //isVisiable = true;
            onHiddenChanged(true);
            isCanLoadData();
        } else {
            //isVisiable = false;
            onHiddenChanged(false);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        hiddenChange(hidden);
    }

    protected void hiddenChange(boolean hidden) {

    }

    private void isCanLoadData() {
        if (!isInit) {
            return;
        }
        if (getUserVisibleHint()) {
            lazyLoad();
            isLoad = true;
        } else {
            if (isLoad) {
                stopLoad();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isInit = false;
        isLoad = false;

    }

    @Override
    public void onResume() {
        super.onResume();
    }

    protected void showToast(String message) {
        if (!TextUtils.isEmpty(message)) {
            Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
        }
    }
    protected abstract int setContentView();
    protected View getContentView() {
        return view;
    }
    protected <T extends View> T findViewById(int id) {

        return (T) getContentView().findViewById(id);
    }
    protected abstract void lazyLoad();
    protected void stopLoad() {
    }

}
